﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using UNDP_Projects.Data_Access;

using UNDP_Projects.Classes;

namespace UNDP_Projects.Project
{
    public partial class Saved_Projects : PdfCreator
    {
        protected void Page_PreInit(object sender, EventArgs e)
        {
            /*if (User.IsInRole("Project"))
            {
                MasterPageFile = "~/MasterPages/Project.Master";
            }
            if (User.IsInRole("Programme"))
            {
                MasterPageFile = "~/MasterPages/Programme.Master";
            }
            if (User.IsInRole("Administrator"))
            {
                MasterPageFile = "~/MasterPages/CO.Master";
            }
            if (User.IsInRole("Project") && User.IsInRole("Programme"))
            {
                MasterPageFile = "~/MasterPages/ProgProject.Master";
            }*/
        }

        UNDPEntities db = new UNDPEntities();

        protected void Page_Load(object sender, EventArgs e)
        {
            
        }

        //protected void SavedProjectsGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
        //{
        //    GridView myGrid = (GridView)sender;

        //    long ProjID = long.Parse(myGrid.DataKeys[e.RowIndex].Values[0].ToString());

        //    if (!User.IsInRole("Administrator"))
        //    {
        //        var UProject = (from u in db.users where u.user_email == User.Identity.Name select u.project_id).Single();
        //        if (UProject == null)
        //        {
        //            Error.Text = "You cant access this project";
        //            Error.Visible = true;
        //            return;
        //        }

        //        string[] theProj = UProject.Split(new Char[] { ',' });

        //        foreach (var UProjAccess in theProj)
        //        {
        //            try
        //            {
        //                long projToAccess = long.Parse(UProjAccess);

        //                if (projToAccess == ProjID)
        //                {
        //                    //myGrid.DeleteRow(e.RowIndex);
        //                    //e.Cancel = false;
        //                    //myGrid.DataBind();
        //                    Error.Text = "Deletion Complete.";
        //                    Error.Visible = true;
        //                }
        //                else
        //                {
        //                    e.Cancel = true;
        //                    Error.Text = "You cannot delete this project";
        //                    Error.Visible = true;
        //                }
        //            }
        //            catch
        //            {
        //                e.Cancel = true;
        //                Error.Text = "You can't delete this project";
        //                Error.Visible = true;
        //            }
        //        }
        //    }
        //    else
        //    {
        //        myGrid.DeleteRow(e.RowIndex);
        //        myGrid.DataBind();
        //        Error.Text = "Deletion Completed.";
        //        Error.Visible = true;
        //    }
        //}

        protected void SavedProjectsGridView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            //Get the selected row
            int currentRowIndex = Convert.ToInt32(e.CommandArgument);
            GridViewRow row = SavedProjectsGridView.Rows[currentRowIndex];

            //Get the Datakeynames for the selected row
            string selPROJ = this.SavedProjectsGridView.DataKeys[currentRowIndex].Values["project_id"].ToString();
            string selYr = this.SavedProjectsGridView.DataKeys[currentRowIndex].Values["year_id"].ToString();
            string selRPRD = this.SavedProjectsGridView.DataKeys[currentRowIndex].Values["report_period_id"].ToString();

            long proj = long.Parse(selPROJ);
            long reportp = long.Parse(selRPRD);
            long year = long.Parse(selYr);

            if (e.CommandName == "access")
            {
                if (!User.IsInRole("Administrator"))
                {
//==================TO DELETE=============================================================================
                    //char[] separator = new char[] { '\\' };
                    //string[] uName = User.Identity.Name.Split(separator);
                    //string uname2 = uName[1] + "@undp.org";
                    //var UProject = (from u in db.users where u.user_email == uname2 select u.project_id).Single();
//===================TO DELETE===============================================================================

                    var UProject = (from u in db.users where u.user_email == User.Identity.Name select u.project_id).FirstOrDefault();
                    if (UProject == null)
                    {
                        Error.Text = "You cant access this project";
                        Error.Visible = true;
                        return;
                    }

                    string[] theProj = UProject.Split(new Char[] { ',' });

                    foreach (var UProjAccess in theProj)
                    {
                        try
                        {
                            long projToAccess = long.Parse(UProjAccess);

                            if (projToAccess == proj)
                            {
                                Session["Project"] = proj;
                                Session["ReportPeriod"] = reportp;
                                Session["Year"] = year;

                                Response.Redirect("~/Project/Project_Report/", true);
                            }
                            else
                            {
                                Error.Text = "You cant access this project";
                                Error.Visible = true;
                            }
                        }
                        catch
                        {
                            Error.Text = "You cant access this project";
                            Error.Visible = true;
                        }
                    }
                }
                else
                {
                    //ProjectLabel.Text = "Project : " + long.Parse(selPROJ);
                    //YearLabel.Text = "Year : " + long.Parse(selYr);
                    //ReportPeriodLabel.Text = "Report period : " + long.Parse(selRPRD);

                    Session["Project"] = proj;
                    Session["ReportPeriod"] = reportp;
                    Session["Year"] = year;

                    Response.Redirect("~/Project/Project_Report/", true);
                }
            }
            else if (e.CommandName == "pdf")
            {
                if (!User.IsInRole("Administrator"))
                {
//=========TO DELETE========================================================================================
                    //char[] separator = new char[] { '\\' };
                    //string[] uName = User.Identity.Name.Split(separator);
                    //string uname2 = uName[1] + "@undp.org";
                    //var UProject = (from u in db.users where u.user_email == uname2 select u.project_id).Single();
//=========TO DELETE=========================================================================================

                    var UProject = (from u in db.users where u.user_email == User.Identity.Name select u.project_id).Single();
                    if (UProject == null)
                    {
                        Error.Text = "You cannot access this project";
                        Error.Visible = true;
                        return;
                    }

                    string[] theProj = UProject.Split(new Char[] { ',' });

                    foreach (var UProjAccess in theProj)
                    {
                        try
                        {
                            long projToAccess = long.Parse(UProjAccess);

                            if (projToAccess == proj)
                            {
                                CreatePDF(proj, reportp, year);
                            }
                            else
                            {
                                Error.Text = "You cannot access this document";
                                Error.Visible = true;
                            }
                        }
                        catch
                        {
                            Error.Text = "You cant access this document";
                            Error.Visible = true;
                        }
                    }
                }
                else
                {
                    CreatePDF(proj, reportp, year);
                }
            }
            //else if (e.CommandName == "delete")
            //{
            //    //Get the selected row
            //    int currentRowIndex = Convert.ToInt32(e.CommandArgument);
            //    GridViewRow row = SavedProjectsGridView.Rows[currentRowIndex];

            //    //Get the Datakeynames for the selected row
            //    string selPROJ = this.SavedProjectsGridView.DataKeys[currentRowIndex].Values["project_id"].ToString();
            //    string selYr = this.SavedProjectsGridView.DataKeys[currentRowIndex].Values["year_id"].ToString();
            //    string selRPRD = this.SavedProjectsGridView.DataKeys[currentRowIndex].Values["report_period_id"].ToString();

            //    long proj = long.Parse(selPROJ);
            //    long rprt = long.Parse(selRPRD);
            //    long yr = long.Parse(selYr);

            //    using (UNDPEntities db = new UNDPEntities())
            //    {
            //        try
            //        {

            //            project_reports selectedProject = db.project_reports.SingleOrDefault(
            //                                                pr => pr.project_id == proj &&
            //                                                pr.report_period_id == rprt &&
            //                                                pr.year_id == yr);

            //            activity_updates projectActivity = db.activity_updates.SingleOrDefault(
            //                                                pr => pr.project_id == proj &&
            //                                                pr.report_period_id == rprt &&
            //                                                pr.year_id == yr);

            //            contextual_analysis projectContext = db.contextual_analysis.SingleOrDefault(
            //                                                    pr => pr.project_id == proj &&
            //                                                    pr.report_period_id == rprt &&
            //                                                    pr.year_id == yr);

            //            cpd_output_results projectCPD = db.cpd_output_results.SingleOrDefault(
            //                                                pr => pr.project_id == proj &&
            //                                                pr.report_period_id == rprt &&
            //                                                pr.year_id == yr);

            //            non_cpd_output_indicators projectNonCPD = db.non_cpd_output_indicators.SingleOrDefault(
            //                                                        pr => pr.project_id == proj &&
            //                                                        pr.report_period_id == rprt &&
            //                                                        pr.year_id == yr);

            //            internal_process_indicators projectInt = db.internal_process_indicators.SingleOrDefault(
            //                                                        pr => pr.project_id == proj &&
            //                                                        pr.report_period_id == rprt &&
            //                                                        pr.year_id == yr);

            //            if (!projectActivity.Equals(null))
            //            {
            //                db.activity_updates.DeleteObject(projectActivity);
            //                db.SaveChanges();
            //            }
            //            else if (!projectContext.Equals(null))
            //            {
            //                db.contextual_analysis.DeleteObject(projectContext);
            //                db.SaveChanges();
            //            }
            //            else if (!projectCPD.Equals(null))
            //            {
            //                db.cpd_output_results.DeleteObject(projectCPD);
            //                db.SaveChanges();
            //            }
            //            else if (!projectNonCPD.Equals(null))
            //            {
            //                db.non_cpd_output_indicators.DeleteObject(projectNonCPD);
            //                db.SaveChanges();
            //            }
            //            else if (!projectInt.Equals(null))
            //            {
            //                db.internal_process_indicators.DeleteObject(projectInt);
            //                db.SaveChanges();
            //            }
            //            db.project_reports.DeleteObject(selectedProject);
            //            db.SaveChanges();
            //        }
            //        catch (Exception ex)
            //        {
            //            //Error.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
            //            //Error.Visible = true;
            //            //throw new Exception("Database error : " + ex.Message + " : " + ex.StackTrace, ex);
            //        }
            //    }
            //}
        }
        protected void SavedProjectsGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ((Button)e.Row.Cells[5].Controls[0]).OnClientClick = 
                    "if (!confirm('Do you really want to delete?')) return;";
            }
        }
    }
}